package com.xuecheng.web.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.AuthInfoHolder;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

@Component
public class AuthInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.取出payload(请求)头
        String payload = request.getHeader("payload");
        //判断非空，因为AuthFilter中存在放行的部分uri
        if (StrUtil.isNotEmpty(payload)) {
            //2.decode解码
            String decode = URLDecoder.decode(payload, "utf-8");
            //3.json转java对象
            AuthInfo authInfo = JSON.parseObject(decode, AuthInfo.class);
            //4.存入threadlocal
            AuthInfoHolder.setAuthInfo(authInfo);
        }
        //5.放行
        return true;
    }

    //移除
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthInfoHolder.remove();
    }
}
